﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BingDesktopChanger.Forms
{
    public partial class frmUpgrade : Form
    {
        public frmUpgrade()
        {
            InitializeComponent();
        }

        private int remainDays;

        private void frmUpgrade_Load(object sender, EventArgs e)
        {
            this.Height = 229;
            this.calPeriod.SelectionStart = DateTime.Today.AddDays(-10);
            this.calPeriod.SelectionEnd = DateTime.Today;
            this.calPeriod.MaxDate = DateTime.Today;
        }
        private void cmdStart_Click(object sender, EventArgs e)
        {
            this.Size = new Size(this.Size.Width, 325);
            this.UseWaitCursor = true;
            this.cmdStart.Enabled = false;
            this.remainDays = this.calPeriod.SelectionEnd.Subtract(this.calPeriod.SelectionStart).Days;
            this.pgbStatus.Value = 1;
            this.pgbStatus.Maximum = this.remainDays;
            this.bgkWorker.RunWorkerAsync();
        }

        private void calPeriod_DateSelected(object sender, DateRangeEventArgs e)
        {
            this.cmdStart.Enabled = (e.End.Subtract(e.Start).Days > 0);
        }

        private void bgkWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ImageReader reader = new ImageReader(new DBImageManager(new FileImageManager()));
            reader.StatusChanged += delegate(object senders, StatusNotificationEventArgs ex)
                                    {
                                        this.bgkWorker.ReportProgress(0, ex);
                                    };
            reader.Upgrade(this.calPeriod.SelectionStart, this.calPeriod.SelectionEnd);
        }
        private void bgkWorker_ProgressChanged(object sender, ProgressChangedEventArgs ex)
        {
            StatusNotificationEventArgs e = (StatusNotificationEventArgs)ex.UserState;
            switch (e.StatusCode)
            {
                case StatusCode.GettingImage:
                    this.lblMainStep.Text = string.Format(
                        "Obteniendo imágen {0}. ({1} de {2})",
                        e.CurrentImageName, e.CurrentImageIndex, e.ImagesCount);
                    break;
                case StatusCode.ProcessingDay:
                    this.lblRemainDays.Text = string.Concat("Días a procesar: ", this.remainDays--);
                    this.pgbStatus.PerformStep();
                    break;
                default:
                    this.lblMainStep.Text = e.StatusText;
                    break;
            }
            this.pnlStatus.Refresh();
        }
        private void bgkWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Close();
        }
    }
}
